#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkDatagram>

//定义服务器的ip和端口
const QString IP = "127.0.0.1";
const quint16 PORT = 8000;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("客户端");
    socket = new QUdpSocket(this);

    connect(socket, &QUdpSocket::readyRead, this, &MainWindow::processResponse);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    // 获取输入框内容
    const QString& text = ui->lineEdit->text();
    // 构造请求
    QNetworkDatagram requestDatagram(text.toUtf8(), QHostAddress(IP), PORT);
    // 发送
    socket->writeDatagram(requestDatagram);
    // 消息添加到列表框
    ui->listWidget->addItem("客户端：" + text);
    // 情况输入框
    ui->lineEdit->setText("");
}

void MainWindow::processResponse()
{
    // 处理收到的数据
    const QNetworkDatagram& responseDatagram = socket->receiveDatagram();
    QString response = responseDatagram.data();
    // 数据显示到界面上
    ui->listWidget->addItem("服务端：" + response);
}
